package com.game.league.articles.dialog;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.game.base.app.base.BaseDialogFragment;
import com.game.base.glideV4.ImageLoader;
import com.game.base.observe.MsgMgr;
import com.game.base.observe.MsgType;
import com.game.base.utils.DecimalUtil;
import com.game.base.utils.toast.ToastUtil;
import com.game.base.view.dialog.DialogUtils;
import com.game.league.R;
import com.game.league.articles.table.Articles;
import com.game.league.databinding.DialogExchangeBinding;
import com.game.league.entrance.user.UserMgr;
import com.game.league.entrance.user.table.User;
import com.game.league.service.InterfaceMgr;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 物品兑换弹框
 * Created by Su on 2019/5/31.
 */
@SuppressLint("ValidFragment")
public class ExchangeDialog extends BaseDialogFragment<DialogExchangeBinding> implements View.OnClickListener {
    private Articles articles;
    private User user;

    private int exchangeNum = 1;   // 兑换数量
    private float totalCoin;        // 总共所需点券

    private boolean isExchangeing = false;  // 是否兑换中，防止快速点击造成多次兑换

    public ExchangeDialog(Articles articles) {
        settWindowAnimations(R.style.AnimScaleInScaleOutOverShoot);
        setGravity(Gravity.CENTER);
        setDialogSizeRatio(0, 0);
        setCanceledOnTouchOutside(false);
        this.articles = articles;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_exchange;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        initView();
        return getContentView();
    }

    private void initView() {
        binding.setClick(this);
        totalCoin = articles.getPrice();
        user = UserMgr.getCurrentUser();
        binding.tvTitle.setText(articles.getTitle());
        binding.tvTotal.setText(totalCoin + " 点券");
        ImageLoader.loadRoundCenterCrop(getActivity(), articles.getImgUrl(), binding.ivImage);
        if (!enoughCoin()) {
            binding.tvTotal.setTextColor(getResources().getColor(R.color.text_red));
            binding.btnSubmit.setText("做任务，赚点券!");
        }
    }

    private boolean enoughCoin() {
        return totalCoin <= user.getCoinRemain();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_close:
                dismissAllowingStateLoss();
                break;
            case R.id.btn_add:
                if (!enoughCoin()) return;
                float tempCoin = DecimalUtil.addFloat(totalCoin, articles.getPrice());
                if (tempCoin > user.getCoinRemain()) {
                    ToastUtil.showShort("点券不足");
                    return;
                }
                totalCoin = tempCoin;
                binding.tvNum.setText(String.valueOf(++exchangeNum));
                binding.tvTotal.setText(totalCoin + " 点券");
                break;
            case R.id.btn_reduce:
                if (exchangeNum == 1) {
                    return;
                }
                binding.tvNum.setText(String.valueOf(--exchangeNum));
                totalCoin = DecimalUtil.reduceFloat(totalCoin, articles.getPrice());
                binding.tvTotal.setText(totalCoin + " 点券");
                break;
            case R.id.btn_submit:
                handleSubmit();
                break;
        }
    }

    private void handleSubmit() {
        if (isExchangeing) return;    // 正在兑换

        isExchangeing = true;
        dismissAllowingStateLoss();
        if (!enoughCoin()) {
            isExchangeing = false;
            MsgMgr.getInstance().sendMsg(MsgType.MT_Switch_Task);
            return;
        }

        DialogUtils.showLoadingDialog(getActivity(), "兑换中...");
        InterfaceMgr.getInstance().exchangeArticles(articles, exchangeNum, new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    updateUserCoin(s);
                    return;
                }
                ToastUtil.showShort("兑换失败");
                resetExchangeState();
            }
        });
    }

    private void updateUserCoin(String ex_objectId) {
        if (!user.reduceCoinNum(user, totalCoin)) {
            ToastUtil.showShort("点券不足");
            return;
        }
        UserMgr.updateUser(user, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                resetExchangeState();
                if (e == null) {
                    MsgMgr.getInstance().sendMsg(MsgType.MT_Exchange_Suc);
                    ToastUtil.showShort("兑换成功");

                    // 更新明细
                    InterfaceMgr.getInstance().setFlowBillList(user, "兑换: " + articles.getTitle(),
                            totalCoin, false, null);
                } else {
                    InterfaceMgr.getInstance().deleteExchangeArticles(ex_objectId);
                    ToastUtil.showShort("兑换失败");
                }
            }
        });
    }

    private void resetExchangeState() {
        isExchangeing = false;
        DialogUtils.closeTipDialog();
    }
}
